package com.fernandomdo.ServiceAdministrator;

// Android imports
import java.util.ArrayList;
import java.util.Calendar;

import net.londatiga.android.ActionItem;
import net.londatiga.android.QuickAction;
import android.app.Activity;
import android.app.ListFragment;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Loader;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.fernandomdo.ServiceAdministrator.Territory.TerritoryListItem;
import com.fernandomdo.ServiceAdministrator.databaseInterface.DatabaseInterface;
import com.fernandomdo.ServiceAdministrator.databaseInterface.DatabaseInterface.DatabaseConstants;


public class ListTerritoryFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
	//private static final String TAG = "ListPublisherFragment";
	
	private static final int TERRITORY = 0;
		
	private Context appContext;
	private DataSetObserver dataObserver;
	private static OnListItemSelectedListener itemSelectedListener;
	
	private static ListView listView;
	private static LoaderManager loaderManager;
	private static DatabaseInterface databaseInterface;
	private static TerritoryListAdapter territoryListAdapter;
	private static long currentlySelectedItemId;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		appContext = getActivity().getApplicationContext();
		databaseInterface = new DatabaseInterface(appContext);
		currentlySelectedItemId = 0;
		
		territoryListAdapter = new TerritoryListAdapter(appContext, new ArrayList<TerritoryListItem>());
	    dataObserver = new DataSetObserver() {
	    	@Override
	    	public void onChanged() {
	    		super.onChanged();	 
	    		setEmptyText(getResources().getString(R.string.list_empty));
	    	}
		};
		
		setListAdapter(territoryListAdapter);
	    
		loaderManager = getLoaderManager();
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			itemSelectedListener = (OnListItemSelectedListener) activity;
		}
		catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + "must implement OnListItemSelectedListener");
		}
	}
	
	@Override
	public void onPause() {
		super.onPause();
		territoryListAdapter.unregisterDataSetObserver(dataObserver);
		if(databaseInterface.readableDB != null) {
			databaseInterface.readableDB.close();
		}
		if(databaseInterface.writableDB != null){
			databaseInterface.writableDB.close();			
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		territoryListAdapter.registerDataSetObserver(dataObserver);
		refreshList();
	}

	public static void refreshList() {
		loaderManager.getLoader(TERRITORY).forceLoad();
	}
	
	public static TerritoryListItem getCurrentlySelectedItem() {
		int count = listView.getChildCount();
		int i;
		for(i=0;i<count;i++) {
			long id;
			try {
				id = listView.getItemIdAtPosition(i);				
			}
			catch (IndexOutOfBoundsException e) {
				id = listView.getItemIdAtPosition(i-1);
			}
			
			if(id == currentlySelectedItemId) {
				return (TerritoryListItem)listView.getItemAtPosition(i);
			}
		}
		if(count == 0) {
			return null;
		}
		else
			return (TerritoryListItem)listView.getItemAtPosition(0);
	}
	
	public interface OnListItemSelectedListener {
		/**
		 * The parent activity must implement this to share information with other fragments
		 * @param item
		 */
		public void onListItemSelected(Object item);	
	}
	
	
	@Override
	public void onListItemClick(ListView listView, View view, int pos, long id) {	
		TerritoryListItem item = (TerritoryListItem)getListView().getItemAtPosition(pos);
		currentlySelectedItemId = id;
		itemSelectedListener.onListItemSelected(item);
	}
	
	
	/**
	 * Called when the ListView that will hold the items has been created
	 * @param view
	 * @param savedInstanceState
	 */
	public void onViewCreated(View view, Bundle savedInstanceState) { 
		listView = getListView();
		// Initialize the loaders...
	    loaderManager.initLoader(TERRITORY, null, this);
		
		listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View listView, int pos, long id) {
				final TerritoryListItem territoryItem = (TerritoryListItem)getListView().getItemAtPosition(pos);

				currentlySelectedItemId = id;
				QuickAction listActions;
				listActions = new QuickAction(appContext);
			    
			    Drawable checkinIcon = appContext.getResources().getDrawable(R.drawable.ac_down);
			    Drawable checkoutIcon = appContext.getResources().getDrawable(R.drawable.ac_up);
				Drawable editIcon = appContext.getResources().getDrawable(R.drawable.ac_pencil);
			    Drawable deleteIcon = appContext.getResources().getDrawable(R.drawable.ac_trash);
			    
			    listActions.addActionItem(new ActionItem(ConfirmDialog.ACTION_CHECKIN, getResources().getString(R.string.action_check_in), checkinIcon));		
				listActions.addActionItem(new ActionItem(ConfirmDialog.ACTION_CHECKOUT, getResources().getString(R.string.action_check_out), checkoutIcon));
				listActions.addActionItem(new ActionItem(ConfirmDialog.ACTION_EDIT, getResources().getString(R.string.action_edit_territory), editIcon));
				listActions.addActionItem(new ActionItem(ConfirmDialog.ACTION_DELETE, getResources().getString(R.string.action_delete_territory), deleteIcon));
				
				
				listActions.mAnimateTrack(false);
				listActions.setAnimStyle(QuickAction.ANIM_GROW_FROM_RIGHT);
				
				
				
				listActions.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {				
					@Override
					public void onItemClick(QuickAction source, int pos, int actionId) {
						Bundle args;
						switch(actionId) {
						case ConfirmDialog.ACTION_CHECKIN:
							ConfirmDialog confirmCheckin = ConfirmDialog.newInstance(databaseInterface, ConfirmDialog.ACTION_CHECKIN, 
									R.string.title_confirm_checkin_territory, territoryItem.id, true);
							confirmCheckin.show(getFragmentManager(), ConfirmDialog.CHECKIN);
							break;
						case ConfirmDialog.ACTION_CHECKOUT:
							//args = new Bundle();
							//CheckoutDialog checkoutDialog = new CheckoutDialog();
							//args.putLong("territory_id", territoryItem.id);
							//checkoutDialog.setArguments(args);
							//checkoutDialog.show(getActivity().getFragmentManager(), "checkout");
							CheckoutDialog checkoutDialog = CheckoutDialog.newInstance(CheckoutDialog.SIMPLE_DIALOG, territoryItem.id);
							checkoutDialog.show(getFragmentManager(), CheckoutDialog.CHECKOUT);
							break;
						case ConfirmDialog.ACTION_EDIT:
							args = new Bundle();
							EditDialog editDialog = new EditDialog();
							
							args.putLong(EditDialog.TERRITORY_ID, territoryItem.id);
							editDialog.setArguments(args);
							editDialog.show(getActivity().getFragmentManager(), EditDialog.EDIT);
							break;
						case ConfirmDialog.ACTION_DELETE:
							ConfirmDialog confirmDelete = ConfirmDialog.newInstance(databaseInterface, ConfirmDialog.ACTION_DELETE, 
									R.string.title_confirm_delete_territory, territoryItem.id, true);
							confirmDelete.show(getFragmentManager(), ConfirmDialog.DELETE);
						default:						
							//mTerritoryForDelete = listActions.getId();
					  		
							break;
						}
					}
				});
				listActions.show(listView);
		    	return true;
			}
		}); 
	}    

		
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Async loaders to get the items from the database
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/**
	 * Simple Loader to retrieve the Territory list
	 */
	static public class TerritoryListLoader extends AsyncLoader<Cursor> {
		public TerritoryListLoader(Context context) {
			super(context);
		}
			
		@Override
		public Cursor loadInBackground() {
			databaseInterface.readableDB = databaseInterface.databaseHelper.getReadableDatabase();
			Cursor cursor;
			final String[] FROM = { BaseColumns._ID, DatabaseConstants.TERRITORY, DatabaseConstants.STATUS };
			final String ORDER_BY = DatabaseConstants.TERRITORY;
			cursor = databaseInterface.readableDB.query(DatabaseConstants.TERRITORY_TABLE,  FROM, null, null, null, null, ORDER_BY);
			//cursor = databaseInterface.readableDB.rawQuery("SELECT rowid _id,name,strftime('%s',started), strftime('%s', finished) FROM territory ORDER BY started DESC", new String[] {});
			return cursor;
		}
	}
	
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		Loader<Cursor> loader = null;
		if(id == TERRITORY){
			loader = new TerritoryListLoader(appContext);
		}
		return loader;
	}
	
	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		if(loader.getId() == TERRITORY) {
		
			ArrayList<TerritoryListItem> data = new ArrayList<TerritoryListItem>();
			while(cursor.moveToNext()) {
				TerritoryListItem item = new TerritoryListItem();
				item.id = Util.cursorFetchLong(cursor, BaseColumns._ID);
				item.name = Util.cursorFetchString(cursor, DatabaseConstants.TERRITORY);
				item.status = Util.cursorFetchBool(cursor, DatabaseConstants.STATUS);

				data.add(item);
			}
			
			territoryListAdapter.swapData(data);			
		}
		
		itemSelectedListener.onListItemSelected(getCurrentlySelectedItem());			
	}
	
	
	/**
	 * Make sure that you override this method when you create an instance of DatabaseInterface
	 */
	
	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		territoryListAdapter.swapData(new ArrayList<TerritoryListItem>());
	}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Confirm Dialog
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	public static void confirmDelete(long territoryId) {
		databaseInterface.deleteTerritory(territoryId);	
		territoryListAdapter.notifyDataSetChanged();
		loaderManager.getLoader(TERRITORY).forceLoad();
	}
	
	public static void confirmCheckin(long territoryId) {
		databaseInterface.checkInTerritory(territoryId, Calendar.getInstance().getTime());	
		territoryListAdapter.notifyDataSetChanged();
		loaderManager.getLoader(TERRITORY).forceLoad();
	}
	
	public static void updateList() {
		territoryListAdapter.notifyDataSetChanged();
		loaderManager.getLoader(TERRITORY).forceLoad();
	}
}
